package ldh.im.base.service;

import ldh.im.ImConfig;
import ldh.im.base.CacheUserManager;
import ldh.im.base.ImSession;
import ldh.im.base.handler.service.HandlerService;
import ldh.im.dto.business.LoginReq;
import ldh.im.dto.business.LoginResp;
import ldh.im.util.RandomCharacter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

public class LoginBusinessService implements BusinessService<LoginReq> {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginBusinessService.class);

    @Override
    public void handle(ImSession imSession, LoginReq loginReq) {
        LOGGER.info(String.format("%s loginReq success!!!!", loginReq.getPassword()));

        Long userId = Math.round(Double.MAX_VALUE);
        try {
            userId = Long.parseLong(loginReq.getUserName());
        } catch (Exception e) {
        }
        String authToken = buildAuth(20);
        int autCode = (int)(Math.random() * 100000);

        imSession.put(ImConfig.CHANNEL_ID, imSession.getChannel().id());
        imSession.put(ImConfig.AUTH_CODE, autCode);
        imSession.put(ImConfig.USER_ID, userId);

        CacheUserManager.getInstance().setCache(userId, ImConfig.AUTH_TOKEN, authToken);
        CacheUserManager.getInstance().setCache(userId, ImConfig.AUTH_CODE, autCode);
        CacheUserManager.getInstance().setCache(userId, ImConfig.CHANNEL_ID, imSession.getChannel().id());

        LoginResp loginRec = new LoginResp();
        loginRec.setLogin(loginReq);
        loginRec.setUserId(userId);
        loginRec.setServerDateTime(LocalDateTime.now());
        loginRec.setSuccessDataTime(LocalDateTime.now());
        loginRec.setAuthToken(authToken);
        loginRec.setAuthCode(autCode);

        imSession.getChannel().writeAndFlush(loginRec);
    }

    private String buildAuth(int length) {
        return RandomCharacter.getRandomCharacter(length);
    }
}
